//basicfunctions.h

#include"headers.h"

void getData( )
{
	int x,y,i,c;
	ifstream input;
        //open file for reading
	input.open ( "input.txt" );
	if ( !input )
	   {
	     cout << "There was an error unable to read file!";
             exit(0);
           }

        input >> c;
        while ( c != 0 )//while not end of input file
          {
             for ( i = 0; i < c; i++) 
               {
 	         input >> x;
       	         input >> y;
                 Node n(x,y);
                 gNetwork.push_back( n );
               }
 
             gAllNetworks.push_back( gNetwork );
             gNetwork.clear();
             input >> c;

          }
        input.close();
}

//solution genetic_engine 
void geneticAlgorithm()
{
	int i,j;
        // for each network in the data given do the following
        for ( i = 0; i <  gAllNetworks.size(); i++)
          {
            gNetwork = gAllNetworks[i];
            gCurrentNetworkNumber++;        
            
            populate();//creates a world of possible solutions
            
            for( j = 0 ; j < NUMBER_OF_GENERATIONS ; j++)
              {
                //choose a group(based on fitness value) of candidate solutions.
                selection();
                // randomly mutate some of the candidates and add the mutated candidates to population
                mutation();
                
               }
              
             //display the solution in the required format
            printSolution(gSolution);
            
             //clearing data of current network
            gCurrentGeneration.clear();
            gNetwork.clear();
            gSolution.clear();
          }
}

void printSolution( vector<int> solution )
{
	int i;
	double underRoot=0,x1,x2,y1,y2;
	cout << "******************************************************"<< endl;
	cout << "network#" << gCurrentNetworkNumber << endl;
	for(i = 0 ; i < solution.size()-1 ; i++)
          {
            x1 = gNetwork[solution[i]-1].X();
            x2 = gNetwork[solution[i+1]-1].X();
            y1 = gNetwork[solution[i]-1].Y();
            y2 = gNetwork[solution[i+1]-1].Y();
            underRoot = ((x1-x2)*(x1-x2) + (y1-y2)*(y1-y2));
        
            cout << "Cable requirement to connect (";
            cout << x1 << "," << y1 << ") to (" << x2 << "," << y2 << ") is ";
            cout << sqrt( underRoot ) + ADDITIONAL_FEET<<endl;
          }
	cout << "Number of feet of cable required is "<< fitness(solution)<< endl;
}

